<template>
  <div class="search-container">
    <input
      v-model="searchTerm"
      type="text"
      placeholder="请输入商品名称进行搜索"
      @input="fetchSearchResults"
      class="search-input"
    />
    <ul v-if="searchResults.length > 0" class="result-list">
      <li
        v-for="product in searchResults"
        :key="product.id"
        class="result-item"
      >
        <!-- 商品图片 -->
        <image class="product-img" :src="Config.API_HOST + product.imgUrl" mode="aspectFill"></image>
        <!-- 商品信息区域 -->
        <view class="product-info">
          <!-- 商品标题 -->
          <text class="product-title">{{ product.name }}</text>
          <!-- 商品已售数量 -->
          <text class="sales">已售{{ product.sales }}</text>
          <!-- 价格容器 -->
          <view class="price-container">
            <!-- 当前价格 -->
            <text class="current-price">¥{{ product.price }}</text>
            <!-- 原价 -->
            <text class="old-price">¥{{ product.oldPrice }}</text>
            <text>超市: {{ getShopName(product.shopId) }}</text>
			
          </view>
		  <button @click="addToCart(product)" class="add">加入购物车</button>
        </view>
        
      </li>
    </ul>
    <p v-else class="no-result">暂无搜索结果</p>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import Config from "@/config.js";
import {onShow} from "@dcloudio/uni-app"
const searchTerm = ref('');
const searchResults = ref([]);
const cart = ref([]);
const shops = ref([]);

const fetchSearchResults = () => {
  if (!searchTerm.value.trim()) {
    searchResults.value = [];
    return;
  }
  uni.request({
    url: Config.API_HOST + '/products-all',
    method: 'GET',
    success: (res) => {
      if (res.statusCode === 200) {
        const data = res.data;
        const filteredResults = data.filter(product =>
          product.name.toLowerCase().includes(searchTerm.value.toLowerCase())
        );
        searchResults.value = filteredResults;
      }
    },
    fail: (err) => {
      console.error('搜索出错:', err);
    }
  });
};

const fetchShops = () => {
  uni.request({
    url: Config.API_HOST + '/hotList',
    method: 'GET',
    success: (res) => {
      if (res.statusCode === 200) {
        shops.value = res.data;
      } 
    },
    fail: (err) => {
      console.error('获取超市信息出错:', err);
    }
  });
};
onShow(()=>{
	fetchShops()
})
const getShopName = (shopId) => {
  const shop = shops.value.find(shop => shop._id === shopId.toString());
  return shop ? shop.name : '未知超市';
};

const addToCart = (product) => {
  const token = uni.getStorageSync("token");
  if (!token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none',
      duration: 2000
    });
	uni.redirectTo({
		url:"/pages/login/index"
	})
    return;
  } else {
	 uni.request({
	   url: `${Config.API_HOST}/carts/?token=${token}`,
	   method: 'GET',
	   success: (res) => {
	     const carts = res.data;
	     const existingItem = carts.find(cartItem => cartItem.id === product.id);
		const shopName = getShopName(product.shopId);
	     if (existingItem) {
	       const newQuantity = existingItem.quantity + 1;
	       uni.request({
	         url: `${Config.API_HOST}/carts/${existingItem.id}`,
	         method: 'PUT',
	         data: {
	           ...existingItem,
	           quantity: newQuantity
	         },
	         success: (updateRes) => {
				 uni.showToast({
				   title: '加入购物车成功',
				   icon: 'success',
				   duration: 2000
				 });
	           fetchShops();
	         },
	         fail: (updateErr) => {
	           console.error('购物车商品数量更新失败', updateErr);
	         }
	       });
	     } else {
	       const cartItem = {
	         ...product,
	         quantity: 1,
	         shopname: shopName,
	         token: uni.getStorageSync('token')
	       };
	       uni.request({
	         url: `${Config.API_HOST}/carts?token=${token}`,
	         method: 'POST',
	         data: cartItem,
	         success: (addRes) => {
				 uni.showToast({
				   title: '加入购物车成功',
				   icon: 'success',
				   duration: 2000
				 });
	           fetchShops();
	         },
	         fail: (addErr) => {
	           console.error('商品添加到购物车失败', addErr);
	         }
	       });
	     }
	   },
	   fail: (err) => {
	     console.error('获取购物车数据失败', err);
	   }
	 });
};
}


</script>

<style scoped>
/* 搜索容器样式 */
.search-container {
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* 搜索输入框样式 */
.search-input {
  border: 1px solid #d1d5db;
  padding: 12px 16px;
  border-radius: 8px;
  margin-bottom: 24px;
  width: 90%;
  font-size: 16px;
  outline: none;
  transition: border-color 0.3s ease;
}

.search-input:focus {
  border-color: #007aff;
}

/* 结果列表样式 */
.result-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

/* 结果项样式 */
.result-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.result-item:hover {
  background-color: #f9fafb;
}

/* 商品图片样式 */
.product-img {
  width: 80px;
  height: 80px;
  margin-right: 16px;
  border-radius: 8px;
  object-fit: cover;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 商品信息区域样式 */
.product-info {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  flex: 1;
}

/* 商品标题样式 */
.product-title {
  font-size: 16px;
  font-weight: 400;
  color: #1f2937;
  margin-bottom: 4px;
}

/* 商品已售数量样式 */
.sales {
  font-size: 12px;
  color: #6b7280;
  margin-bottom: 8px;
}

/* 价格容器样式 */
.price-container {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

/* 当前价格样式 */
.current-price {
  font-size: 16px;
  font-weight: 500;
  color: #ef4444;
}

/* 原价样式 */
.old-price {
  font-size: 12px;
  color: #9ca3af;
  text-decoration: line-through;
}

/* 加入购物车按钮样式 */
.add {
 margin-left: 2px;
  padding: 2px 8px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  font-size: 11px;
}

.add:hover {
  background-color: #0056b3;
}

/* 暂无搜索结果提示样式 */
.no-result {
  color: #9ca3af;
  font-size: 16px;
  text-align: center;
  padding: 24px;
}
</style>    